#include "dbmanager.h"
#include <QDebug>

DBManager& DBManager::getInstance()
{
    static DBManager instance;
    return instance;
}

DBManager::DBManager()
{
    db = QSqlDatabase();
}

bool DBManager::openDatabase(const QString &dbName)
{
    if (!db.isOpen()) {
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(dbName);
        if (!db.open()) {
            qCritical() << "DBManager Failed to connect to the database: " << db.lastError().text();
            return false;
        } else {
            qInfo() << "DBManager Connected to database: " << dbName;
            this->m_dbName=dbName;
            qDebug()<< "this->m_dbName "<<this->m_dbName;
        }
    }
    return true;
}

bool DBManager::isOpen() const
{
    return db.isOpen();
}

QSqlQuery DBManager::execQuery(const QString &query)
{
    QSqlQuery q(db);
    if (!q.prepare(query)) {
        qCritical() << "Failed to prepare query: " << q.lastError().text();
        return QSqlQuery();
    }
    if (!q.exec()) {
        qCritical() << "Database error: " << q.lastError().text();
    }
    return q;
}

void DBManager::closeDatabase()
{
    if (db.isOpen()) {
        db.close();
        qInfo() << "Database connection closed.";
    }
}

DBManager::~DBManager()
{
    closeDatabase();
}

bool DBManager::insertIntoIconTable( const QString &fileName, const QString &filePath)
{
    if (!isOpen()) {
        if (!openDatabase(m_dbName)) {
            return false;
        }
    }
    QSqlQuery query;
    query.prepare("INSERT INTO Icon (Name, Path) VALUES (?, ?)");
    query.addBindValue(fileName);
    query.addBindValue(filePath);
    if (!query.exec()) {
        qCritical() << "Failed to insert into Icon table: " << query.lastError().text();
        return false;
    }
    return true;
}
